package com.ml.loan.common.utils;

import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author Mickey
 * @Date 2021/3/25 16:48
 **/
@Slf4j
public class RSAUtil {

    public static final String KEY_ALGORITHM = "RSA";

    /**
     * 签名算法
     **/
    private static final String signAlgorithmSHA1 = "SHA1withRSA";
    private static final String signAlgorithmSHA256 = "SHA256withRSA";
    private static final String signAlgorithmMD5 = "MD5withRSA";

    private static final String PUBLIC_KEY = "RSAPublicKey";
    private static final String PRIVATE_KEY = "RSAPrivateKey";

    public static byte[] decryptBASE64(String key) {
        return Base64.getDecoder().decode(key);
    }

    public static String encryptBASE64(byte[] bytes) {
        return Base64.getEncoder().encodeToString(bytes);
    }

    public static String signMD5(String content, String privateKey) {
        return sign(signAlgorithmMD5, content.getBytes(StandardCharsets.UTF_8), privateKey);
    }

    public static String signSHA1(String content, String privateKey) {
        return sign(signAlgorithmSHA1, content.getBytes(StandardCharsets.UTF_8), privateKey);
    }

    public static String signSHA256(String content, String privateKey) {
        return sign(signAlgorithmSHA256, content.getBytes(StandardCharsets.UTF_8), privateKey);
    }

    public static boolean verifySignMD5(String content, String sign, String publicKey) {
        return verify(signAlgorithmMD5, content.getBytes(StandardCharsets.UTF_8), publicKey, sign);
    }

    public static boolean verifySignSHA1(String content, String sign, String publicKey) {
        return verify(signAlgorithmSHA1, content.getBytes(StandardCharsets.UTF_8), publicKey, sign);
    }

    public static boolean verifySignSHA256(String content, String sign, String publicKey) {
        return verify(signAlgorithmSHA256, content.getBytes(StandardCharsets.UTF_8), publicKey, sign);
    }


    /**
     * 用私钥对信息生成数字签名
     *
     * @param data       加密数据
     * @param privateKey 私钥
     * @return
     * @throws Exception
     */
    public static String sign(String signAlgorithm, byte[] data, String privateKey) {
        try {
            // 解密由base64编码的私钥
            byte[] keyBytes = decryptBASE64(privateKey);
            // 构造PKCS8EncodedKeySpec对象
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
            // KEY_ALGORITHM 指定的加密算法
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            // 取私钥匙对象
            PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);
            // 用私钥对信息生成数字签名
            Signature signature = Signature.getInstance(signAlgorithm);
            signature.initSign(priKey);
            signature.update(data);
            return encryptBASE64(signature.sign());
        } catch (Exception e) {
            log.error("生成签名异常:{}", e.getMessage(), e);
        }
        return null;
    }

    /**
     * 校验数字签名
     *
     * @param data      加密数据
     * @param publicKey 公钥
     * @param sign      数字签名
     * @return 校验成功返回true 失败返回false
     * @throws Exception
     */
    public static boolean verify(String signAlgorithm, byte[] data, String publicKey, String sign) {
        try {
            // 解密由base64编码的公钥
            byte[] keyBytes = decryptBASE64(publicKey);
            // 构造X509EncodedKeySpec对象
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
            // KEY_ALGORITHM 指定的加密算法
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            // 取公钥匙对象
            PublicKey pubKey = keyFactory.generatePublic(keySpec);
            Signature signature = Signature.getInstance(signAlgorithm);
            signature.initVerify(pubKey);
            signature.update(data);
            // 验证签名是否正常
            return signature.verify(decryptBASE64(sign));
        } catch (Exception e) {
            log.error("验证签名失败:{}", e.getMessage(), e);
        }
        return false;
    }

    /**
     * 私钥解密
     *
     * @param data
     * @param privateKey
     **/
    public static String decryptByPrivateKeyStr(String data, String privateKey) {
        try {
            return new String(decryptByPrivateKey(data, privateKey));
        } catch (Exception e) {
            log.error("私钥解密失败:{}", e.getMessage(), e);
        }
        return null;
    }

    /**
     * 解密<br>
     * 用私钥解密
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPrivateKey(String data, String key)
            throws Exception {
        return decryptByPrivateKey(decryptBASE64(data), key);
    }

    /**
     * 私钥解密
     *
     * @param data
     * @param key
     **/
    public static byte[] decryptByPrivateKey(byte[] data, String key) throws Exception {
        // 对密钥解密
        byte[] keyBytes = decryptBASE64(key);
        // 取得私钥
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        // 对数据解密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return cipher.doFinal(data);
    }


    /**
     * 公钥加密
     *
     * @param data
     * @param publicKey
     **/
    public static String encryptByPublicKeyStr(String data, String publicKey) {
        try {
            return encryptBASE64(encryptByPublicKey(data, publicKey));
        } catch (Exception e) {
        }
        return null;
    }


    /**
     * 加密<br>
     * 用公钥加密
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPublicKey(String data, String key)
            throws Exception {
        // 对公钥解密
        byte[] keyBytes = decryptBASE64(key);
        // 取得公钥
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicKey = keyFactory.generatePublic(x509KeySpec);
        // 对数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return cipher.doFinal(data.getBytes());
    }

    /**
     * 取得私钥
     *
     * @param keyMap
     * @return
     * @throws Exception
     */
    public static String getPrivateKey(Map<String, Key> keyMap) {
        Key key = keyMap.get(PRIVATE_KEY);
        return encryptBASE64(key.getEncoded());
    }

    /**
     * 取得公钥
     *
     * @param keyMap
     * @return
     * @throws Exception
     */
    public static String getPublicKey(Map<String, Key> keyMap) {
        Key key = keyMap.get(PUBLIC_KEY);
        return encryptBASE64(key.getEncoded());
    }

    /**
     * 初始化密钥
     *
     * @return
     * @throws Exception
     */
    public static Map<String, Key> initKey() throws Exception {
        KeyPairGenerator keyPairGen = KeyPairGenerator
                .getInstance(KEY_ALGORITHM);
        keyPairGen.initialize(1024);
        KeyPair keyPair = keyPairGen.generateKeyPair();
        Map<String, Key> keyMap = new HashMap(2);
        keyMap.put(PUBLIC_KEY, keyPair.getPublic());// 公钥
        keyMap.put(PRIVATE_KEY, keyPair.getPrivate());// 私钥
        return keyMap;
    }


    public static void main(String[] args) throws Exception {
        String publicKey;
        String privateKey;

        Map<String, Key> keyMap = initKey();
        publicKey = getPublicKey(keyMap);
        privateKey = getPrivateKey(keyMap);
        System.err.println("公钥: \n\r" + publicKey);
        System.err.println("私钥： \n\r" + privateKey);

        String data = "测试123";

        String signMD5 = signMD5(data, privateKey);
        boolean verifySignMD5 = verifySignMD5(data, signMD5, publicKey);
        System.out.println("MD5签名===>" + signMD5 + " MD5验签=========>" + verifySignMD5);

        String signSHA1 = signSHA1(data, privateKey);
        boolean verifySignSHA1 = verifySignSHA1(data, signSHA1, publicKey);
        System.out.println("SHA1签名===>" + signSHA1 + " SHA1验签=========>" + verifySignSHA1);

        String signSHA256 = signSHA256(data, privateKey);
        boolean verifySignSHA256 = verifySignSHA256(data, signSHA256, publicKey);
        System.out.println("SHA256签名===>" + signSHA256 + " SHA256验签=========>" + verifySignSHA256);

        String publicKeyData = encryptByPublicKeyStr(data, publicKey);
        System.out.println("公钥加密：" + publicKeyData);

        String privateKeyData = decryptByPrivateKeyStr(publicKeyData, privateKey);
        System.out.println("私钥解密：" + privateKeyData);

        RSA rsa = new RSA(privateKey, null);
        System.out.println("hutool工具私钥解密：" + new String(rsa.decrypt(publicKeyData, KeyType.PrivateKey)));


        System.out.println(System.currentTimeMillis());

        System.out.println(encryptByPublicKeyStr("131406017781616738948030vYu09qh*8M@u&df(", "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDAXcpJAsgNMFcpFKpsRH7Z7cXzVP2i5i7Qq/TbZQKZ9mHVFvMUHC2eU4hBt8Kf4PpCCUNEiriG4QuQQXn++rC8LMhhzLQgfhp+Ws0H0jfg/L8iYwvh71u0j/6PjYy7L8wpX451nXrXV0j3FIroSRDx397SLPB34jHr9G46BD9CuwIDAQAB"));


        String p = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKtVbTTUCAB/lbbKY4VWg+PPuebsK9Ml2OFJCy4Cw6z50ZRxWmDPpkhnXPW3tNuEJrqVIRZwcBaq9qHZVXYFHbqxaREncAOc6vpoazDRy19PeHhZ717PpkwIpc3qqjI6uOGEqUoKSp0hU3E5TCMGiniSvEl6ChoN5P3g9xf37wxfAgMBAAECgYEAjDEtV5G7LnU3EseOIVeGOc0KJ1rODUqlqMl03WQjqpELnTQXKKogPJRfKyvzT79VVUybM1ozTUj837gOxrAu/ux+c1BJ8eP5oyIUdgKMT/IymZCofwBCxQ3DW8aBFQVUunrTuCn0NA97cobh46UYa6mCjC5n7qzxXKU7ON2KVokCQQD7405qaWmmxMvuPBNXxNiE5EyoQCHwAtWingZKiWW0AIMuovGjLZ7CeYEzHu/WXWcs0nm7R8kZuwUnN0lplYzFAkEAriF3huXtk55F6K1/riyIrenqa16bvdXvc8+GxJ7U+85OMV6w5xvvCwTzSHqrDRjgJDMe8bq3PpucfbuE+ihO0wJANtCyoemqukYdcwzT0MffrpvYKs06FXcocqkdCV95KIDsC1weZbpp0DyM50kWPHo7F7/+CcmHc/gFGRGpAjcvWQJAZrt18k9q6AGjyw+5WYAKr1hnJituBQTXveK85vmyPFFODpCIHAF9+WlVQvikPBjl/FVwtzrqa3SRUhi07oWjYwJBAM9T4+W5VnwZFo8VSkZcg6iyDrgBfMzpOyekl86CXDrGm6UcSTsl70R26qwGA5+d2WjPTvWOW0yHAJUICAmO1hY=";
        long l = System.currentTimeMillis();
        System.out.println(l);
        System.out.println(signMD5("admin" + "123456" + l + "Bv#$Yu09qh*8M@u&df(", p));

    }

}
